package com.runvp.common.hex;


/**
 * 一个十进制转十六进制计算器
 */
public class HexCalculator {
    public static final int HEX = 16;

    public static void main(String[] args) {
        char value = 7;
        System.out.println(calculate(value));
        toHex("D,S,T,L,I,I,P,60,00,00,00,07,220,L,H,Y");
        toby("0");
    }
    public static void toby(String str){
        int sf = Integer.parseInt(str, 16);
        System.out.println("sss = "+sf);
        byte [] bytes = new byte[str.length()];
        char [] chars = str.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            bytes[i] = (byte) chars[i];
        }
        System.out.println(bytes);
    }
    public static String toHex(String str){
        String [] srr = str.split(",");
        StringBuilder hex = new StringBuilder();
        String a;
        for (int i = 0; i < srr.length; i++) {
            a = srr[i];
            if(isNumber(a)){
                hex.append(calculate((char) Integer.parseInt(a)));
            }else {
                hex.append(calculate(a.charAt(0)));
            }
        }
        System.out.println(hex.toString());
        return hex.toString();
    }

    public static boolean isNumber(String str){
        try {
            Integer.parseInt(str);
            return true;
        }catch (Exception e){
            return false;
        }
    }

    public static String calculate(char value) {
        char[] result;
        int numOfBit = 1;
        int hex = HEX;
        while(hex <= value) {
            numOfBit++;
            hex *= HEX;
        }
        int index = 0;
        int left = value;
        result = new char[numOfBit];
        while(numOfBit > 0) {
            numOfBit--;
            hex /= HEX;
            result[index] = calHexBit(left / hex);
            left = value % hex;
            index++;
        }
        String ret = String.valueOf(result);
        if(result.length<2){
            return "0"+ret;
        }
        return ret;
    }

    /**
     * @param value from 0 to 15 decimal number.
     * @return a char present hex number.
     */
    public static char calHexBit(int value) {
        switch(value) {
            case 10:
                return 'A';
            case 11:
                return 'B';
            case 12:
                return 'C';
            case 13:
                return 'D';
            case 14:
                return 'E';
            case 15:
                return 'F';
            default:
                return (char) ('0' + value);
        }
    }

}